import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { SessionService } from '@core/session.service';
import { XConsole } from '@core/utils/XConsoleUtil';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  private xConsole: XConsole;
  constructor(
    private _router: Router,
    private _session: SessionService
  ) {
    this.xConsole = new XConsole();
  }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this._session.isLoggedIn) {
      this.xConsole.log(`当前用户已登录!`);
      return true;
    } else if (this._session.canRetry) {
      const result = this._session.checkUserDetail();
      return !!result;
    } else {
      this.xConsole.log(`当前用户未登录，跳转到登录页面`);
      this._router.navigate([this._session.loginUrl]);
      return false;
    }

  }

}
